package uclick.messenger.client;

import uclick.messenger.client.action.ProtocolAction;
import uclick.messenger.client.action.ProtocolRequestFactory;
import uclick.messenger.client.action.request.RequestChattMessageAction;
import uclick.messenger.client.protocol.Protocol;


public class ProtocolRequestEventHandler extends Thread{

	private ProtocolRequestFactory actionFactory  = ProtocolRequestFactory.getEventActionFactory();
	private Protocol protocol;
	private static ProtocolRequestEventHandler eventHandler;
	
	
	private ProtocolRequestEventHandler() {
		super();
	}
	public static ProtocolRequestEventHandler getEventHandler() {
		if(eventHandler==null){
			eventHandler = new ProtocolRequestEventHandler();
			eventHandler.start();
		}
		return eventHandler;
	}
	public synchronized void setProtocol(Protocol protocol) {
		this.protocol = protocol;
		while(this.protocol==null){
			System.out.println("wait");
			try {
				this.wait();
			} catch (InterruptedException e) {
				
			}
		}
		if(this.protocol!=null){
			System.out.println("notify");
			this.notify();
		}
	}
	
	public synchronized void run(){
		Thread currentThread = Thread.currentThread();
		while(currentThread ==this){
			System.out.println("run-processor");
			setProtocol(protocol);
			if(getProtocol(protocol)==Protocol.GENERAL_MSG){
				RequestChattMessageAction.requestExcute(protocol);
			}else{
				ProtocolAction request = actionFactory.getEventAction(protocol);
				request.requestExcute(protocol);
			}
			
			initialize();
		}
	}
	private int getProtocol(Protocol protocol){
		return (Integer)protocol.getContent("protocol");
	}
	private void initialize(){
		if(protocol!=null){
			protocol=null;
		}
	}
}
